package com.codeworker.it.demo.generator;

import com.codeworker.it.demo.config.S3Configuration;
import com.codeworker.it.demo.handler.S3Handler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * S3 Bean对象生成器
 *
 * @author xin
 * @since 2023-07-17
 */
@Component
public class S3Generator implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
    private S3Configuration s3Configuration;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        List<S3Configuration.S3SingleConfiguration> s3ConfigurationList = s3Configuration.getS3ConfigList();
        if (s3ConfigurationList.isEmpty()) {
            return;
        }
        for (S3Configuration.S3SingleConfiguration singleConfiguration : s3ConfigurationList) {
            beanDefinitionRegistry.registerBeanDefinition(singleConfiguration.getBeanName(), BeanDefinitionBuilder
                    .genericBeanDefinition(S3Handler.class)
                    .addPropertyValue("config", singleConfiguration)
                    .getBeanDefinition());
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

    @Override
    public void setEnvironment(Environment environment) {
        BindResult<S3Configuration> bindResult = Binder.get(environment).bind(S3Configuration.PREFIX, S3Configuration.class);
        s3Configuration = bindResult.get();
    }
}
